from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, permissions
from .models import Song, Playlist, PlayHistory
from .serializers import SongSerializer, PlaylistSerializer, PlayHistorySerializer


# 获取所有歌曲
class SongListAPIView(APIView):

    def get(self, request):
        songs = Song.objects.all()
        serializer = SongSerializer(songs, many=True, context={"request": request})  # ✅ 传入 request
        return Response(serializer.data)


# 获取单首歌曲详情
class SongDetailAPIView(APIView):
    def get(self, request, pk):
        try:
            song = Song.objects.get(pk=pk)
        except Song.DoesNotExist:
            return Response({'detail': '未找到该歌曲'}, status=404)
        serializer = SongSerializer(song, context={"request": request})
        return Response(serializer.data)


# 所有歌单
class PlaylistListAPIView(APIView):
    def get(self, request):
        playlists = Playlist.objects.all()
        serializer = PlaylistSerializer(playlists, many=True)
        return Response(serializer.data)


# 歌单详情
class PlaylistDetailAPIView(APIView):
    def get(self, request, pk):
        try:
            playlist = Playlist.objects.get(pk=pk)
        except Playlist.DoesNotExist:
            return Response({'detail': '未找到该歌单'}, status=404)
        serializer = PlaylistSerializer(playlist)
        return Response(serializer.data)


# 播放记录（当前用户）
class PlayHistoryListAPIView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        histories = PlayHistory.objects.filter(user=request.user)
        serializer = PlayHistorySerializer(histories, many=True)
        return Response(serializer.data)

    def post(self, request):
        song_id = request.data.get('song_id')
        try:
            song = Song.objects.get(pk=song_id)
        except Song.DoesNotExist:
            return Response({'detail': '歌曲不存在'}, status=404)
        history = PlayHistory.objects.create(user=request.user, song=song)
        serializer = PlayHistorySerializer(history)
        return Response(serializer.data, status=201)
